import React, {useState, useEffect} from "react";
import {Button, Form, Input, Select, ConfigProvider, Space, Table, message, Modal, Tooltip} from 'antd';
import {
  SyncOutlined,
  SearchOutlined,
  DownOutlined,
  RightOutlined, WarningOutlined,
} from '@ant-design/icons';
// import classes from './index.module.scss';
// import UserModal from "./component/userModal";
import { apiInterceptors, getApplication, deleteApplicationById, getTenantList, getSpaceList, getRole } from '@/client/api';
const { confirm } = Modal
import useSetTableScroll from '@/hooks/use-table-scroll'
import ApplicationModal from './components/applicationModal'

const Application = () => {
  const [queryForm] = Form.useForm();

  const [handleType, setHandleType] = useState('add')
  const [isModalOpen, setIsModalOpen] = useState(false)
  let [tableData, setTableData] = useState([])
  const [appId, setAppId] = useState('')
  const [tenantId, setTenantId] = useState('')
  const [tenantOptions, setTenantOptions] = useState([])
  const [knowledgeOptions, setKnowledgeOptions] = useState([])
  const [roleOptions, setRoleOptions] = useState([])
  let [pagination, setPagination] = useState({
    total: 0,
    current: 1,
    pageSize: 10
  })
  const tableHeight = useSetTableScroll()
  const filterOption = (input: string, option: { label: string; value: string }) => option?.label.includes(input)

  const columns = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '所属租户',
      dataIndex: 'tenant_name',
      key: 'tenant_name',
    },
    {
      title: '关联知识库',
      dataIndex: 'knowledge_names',
      key: 'tenant_name',
      render:(_:any, record:any) => {
        return (
        <Tooltip title={record.knowledge_names.toString()}>
          <span>{record.knowledge_names.toString()}</span>
        </Tooltip>
        )
      }
    },
    {
      title: '关联角色',
      dataIndex: '',
      key: '',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: '',
      render: (_:any, record: any) => {
        return record.status === '1' ? '启用': '禁用'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
      render: (_: any, record: any) => {
        return (
          <Tooltip title={record.desc}>
            <span>{record.desc}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '操作',
      render: (_:any, record:any) => (
        <Space size="middle">
          <a onClick={() => updateApp(record)}>修改</a>
          <a onClick={() => deleteApplication(record)}>删除</a>
        </Space>
      )
    }
  ]

  const paginationChange = (page:number, size:number) => {
    const {total} = pagination
    setPagination({
      total: total,
      current: page,
      pageSize: size
    })
  }
  const getAllTenantList = async () => {
    const [_, result] = await apiInterceptors(getTenantList({page_num: 1, page_size: 9999}))
    const optionList = result.data.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setTenantOptions(optionList)
  }
  const getKnowledgeList = async () => {
    const [_, result] = await apiInterceptors(getSpaceList())
    const optionList = result.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setKnowledgeOptions(optionList)
  }
  const getAllRoleList = async () => {
    const [_, result] = await apiInterceptors(getRole({page_num: 1, page_size: 9999}))
    const optionList = result.data.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setRoleOptions(optionList)
  }
  function searchQueryFn() {
    console.log(queryForm.getFieldsValue())
    setPagination({ ...pagination, current: 1 })
    getTableList()

  }
  function resetQueryFn() {
    queryForm.resetFields()
    setPagination({ ...pagination, current: 1 })
    getTableList()
  }
  function setModal(e: boolean) {
    setIsModalOpen(e)
  }
  const updateApp = (data:any) => {
    setHandleType('edit')
    setAppId(data.id)
    setTenantId(data.tenant_id)
    setModal(true)
  }
  const deleteApplication = (data:any) => {
    confirm({
      title: '提示',
      icon: <WarningOutlined />,
      content: `你确定删除该应用吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk() {
        const [err] = await apiInterceptors(deleteApplicationById(data.id))
        if (!err) {
          message.success('删除成功')
          searchQueryFn()
        }
      },
    });
  }

  const getTableList = async () => {
    const queryData = queryForm.getFieldsValue()
    const param = {
      page_num: pagination.current,
      page_size: pagination.pageSize,
      ...queryData,
    }
    const [_, data] = await apiInterceptors(getApplication(param))
    setTableData(data?.data)
    setPagination({
      pageSize: pagination.pageSize,
      total: data?.total,
      current: pagination.current
    })
  }
  const createHandle = () => {
    setHandleType('add')
    setModal(true)
  }
  useEffect(() => {
    getTableList()
  }, [pagination.current, pagination.pageSize])
  useEffect(() => {
    getAllTenantList()
    // getKnowledgeList()
    getAllRoleList()
  }, [])
  return (
    <div className="p-5 marvel_table_container">
      <div className="top_search p-5 bg-white dark:bg-[#232734]">
        <Form form={queryForm} layout="inline" name={'query'} autoComplete="off" className='cus_form'
              initialValues={{status: '1'}}
              labelAlign='left'
        >
          <Form.Item label="应用名称" name="name">
            <Input style={{ width: 240 }} placeholder="请输入应用名称" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          <Form.Item label="所属租户" name="tenant_id">
            <Select
              style={{width: 240}}
              allowClear
              filterOption={filterOption}
              placeholder="请选择所属租户"
              onChange={searchQueryFn}
              options={tenantOptions}
            />
          </Form.Item>
{/*          <Form.Item label="关联知识库" name="knowledge_ids">
            <Select
              mode="multiple"
              allowClear
              style={{width: 240}}
              filterOption={filterOption}
              placeholder="请选择关联知识库"
              onChange={searchQueryFn}
              options={knowledgeOptions}
            />
          </Form.Item>*/}
          <Form.Item label="关联角色" name="role_ids">
            <Select
              mode="multiple"
              allowClear
              style={{width: 240}}
              filterOption={filterOption}
              placeholder="请选择关联角色"
              onChange={searchQueryFn}
              options={roleOptions}
            />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              style={{ width: 240 }}
              placeholder="请选择状态"
              onChange={searchQueryFn}
              options={[
                { value: '1', label: '启用' },
                { value: '0', label: '禁用' },
              ]}
            />
          </Form.Item>
          <Form.Item label=''>
            <div style={{width: 240}}>
              <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />} style={{marginRight: '20px'}}>
                搜索
              </Button>
              <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                重置
              </Button>
            </div>
          </Form.Item>
          {/*</Space>*/}
        </Form>
      </div>
      <Button type="primary" style={{marginTop: '20px'}} onClick={() => createHandle()}>创建应用</Button>
      <div className="user_table" style={{marginTop: '20px'}}>
        <Table
          columns={columns}
          dataSource={tableData}
          scroll={{y: tableHeight}}
          pagination={{
            ...pagination,
            showTotal: (total, range) => `共 ${total} 条`,
            onChange: paginationChange
          }}
        />
      </div>
      {
        isModalOpen &&
        <ApplicationModal
            handleType={handleType}
            tenantId={tenantId}
            isModalOpen={isModalOpen} setModal={ setModal } appId={appId} successCall={searchQueryFn}/>
      }
    </div>
  )
}

export default Application
